/**
 * @name topology
 * @author Sowmya Balasubramanian, Aaron Hong, David Robertson
 */

function TopologyParams() {
    this.topologyData = undefined;
    this.geoTopologyData = undefined;
    this.retries = 0;
}

function getTopology(layoutType){
    if (!wm.weathermap.flash) {
        var viewNE = wm.renderer.map.getBounds().getNorthEast();
        var viewSW = wm.renderer.map.getBounds().getSouthWest();
        var topoReqParams = "{layoutType:'" + layoutType +
            "',latNW:" + viewNE.lat() + ", lngNW=" + viewSW.lng() + ",latSE:" +
            viewSW.lat() + ", lngSE=" + viewNE.lng() + "}";
    } else {
        try {
            var viewNELat = getFlexApp('weathermap').getCoord("N");
        } catch (e) {
            wm.topology.retries++;
            if (wm.topology.retries < 3) {
                alert("Problem with Flash.  If nothing displays, you will need to refresh the page.");
            }
        }
        var viewNELng = getFlexApp('weathermap').getCoord("E");
        var viewSWLat = getFlexApp('weathermap').getCoord("S");
        var viewSWLng = getFlexApp('weathermap').getCoord("W");
        var topoReqParams = "{layoutType:'" + layoutType +
            "',latNW:" + viewNELat + ", lngNW=" + viewSWLng + ",latSE:" +
            viewSWLat + ", lngSE=" + viewNELng + "}";
    }
    if (layoutType == "geo" && wm.topology.geoTopologyData != undefined) {
        wm.topology.topologyData = wm.topology.geoTopologyData;
        GEvent.trigger(wm.weathermap.eventDummy, "topologyChanged");
    } else {
        GDownloadUrl(servletUrl + "servlet?action=getTopology&topologyRequest="+topoReqParams, function(data) {
            if (typeof(JSON) === 'object' &&
                typeof(JSON.parse) === 'function') {
                wm.topology.topologyData = JSON.parse(data); // native parsing available
            } else {
                wm.topology.topologyData = eval("(" + data + ")");
            }
            //console.log("hi",wm.topology.topologyData);
            if (layoutType == "geo") {
                wm.topology.geoTopologyData = wm.topology.topologyData;
            }

            GEvent.trigger(wm.weathermap.eventDummy, "topologyChanged");
        });
    }
}

function prepareNodesForMap(){
    markersOnMap = new Object();
    var topologyTypes = new Object();
    if (wm.weathermap.demoMode != "globe") {
        if (wm.weathermap.showSdn) {
            topologyTypes["SDN"] = true;
        }
        if (wm.weathermap.showIp) {
            topologyTypes["IP"] = true;
        }
        if (wm.weathermap.showPeers) {
            topologyTypes["PEER"] = true;
        }
    } else {
        topologyTypes["SDN"] = true;
        topologyTypes["IP"] = true;
        topologyTypes["PEER"] = true;
    }
    for (topologyType in topologyTypes) {
        thisTopologyData = wm.topology.topologyData[topologyType];
        for (tmpLod in thisTopologyData) {
            if (tmpLod != wm.weathermap.lod) {
                continue;
            }
            tmpNodes = thisTopologyData[tmpLod].nodes;
            for (nodeName in tmpNodes){
                var node = tmpNodes[nodeName];
                if (wm.weathermap.showSites || 
                        ((node.type != "site") && (node.type != "siteAggr"))) {
                    if (!wm.weathermap.showPeers && ((node.type == "peer") ||
                                       (node.type == "peerAggr"))) {
                        continue;
                    }
                    // kludge for SC09
                    if (wm.weathermap.peersOnly && (topologyType != "PEER") &&
                       (nodeName != "SC09")) {
                        continue;
                    }
                    var addr = node.latitude +","+node.longitude;
                    var point = new GLatLng(node.latitude, node.longitude);
                    if (!wm.weathermap.showSites && (node.type == "siteRouterAggr")) {
                        var marker = createMarker(point, "hub", node.name, addr);
                    } else {
                        var marker = createMarker(point, node.type, node.name, addr);
                    }
                }
            }
        }
    }
}

function prepareLinksForMap() {
    if (wm.topology.topologyData == undefined) return;
    console.log("making ALL polylines");
    var showTopologyTypes;
    if (!wm.weathermap.peersOnly) {
        showTopologyTypes = {SDN: wm.weathermap.showSdn, IP: wm.weathermap.showIp, PEER: wm.weathermap.showPeers};
    } else {
        showTopologyTypes = {SDN: wm.weathermap.saveShowSdn, IP: wm.weathermap.saveShowIp, PEER: true};
    }
    var showLods = new Object();
    showLods[wm.weathermap.lod] = true;
    for (topologyType in showTopologyTypes) {
        if (showTopologyTypes[topologyType]) {
            console.log("type: " + topologyType);
            for (currentLod in showLods) {
                if (showLods[currentLod]) {
                    createLinksForView(topologyType, currentLod);
                }
            }
        }
    }
    console.log("to end of prepareLinksForMap");
}

function createLinksForView(topologyType, currentLod){
    var topoView = wm.topology.topologyData[topologyType][currentLod];
    var connections = topoView.connections;
    var nodes = topoView.nodes;
    var connection;

    for (linkName in connections){
        // kludge for SC09
        if (!wm.weathermap.peersOnly || (topologyType == "PEER")) {
            connection  = connections[linkName];
        } else if ((topologyType == "IP") || (topologyType == "SDN")) {
            if (linkName.indexOf("SC09") == -1) {
                continue;
            } else {
                connection  = connections[linkName];
            }
        }
        var toNode = nodes[connection.dst];
        var fromNode = nodes[connection.src];
        if (!wm.weathermap.showSites &&
                ((toNode.type == "site") || (toNode.type == "siteAggr") ||
                 (fromNode.type == "site") || (fromNode.type == "siteAggr"))) {
            continue;
        }
        if (!wm.weathermap.showPeers &&
                ((toNode.type == "peer") || (toNode.type == "peerAggr") ||
                 (fromNode.type == "peer") || (fromNode.type == "peerAggr"))) {
            continue;
        }
        var to   = new GLatLng(toNode.latitude, toNode.longitude);
        var from = new GLatLng(fromNode.latitude, fromNode.longitude);
        var index = connection.idx;
        var cap   = connection.capacity;
        createLink(linkName, to, from, index, cap);

        if (wm.metrics.metricsData != undefined) {
            var metrics = wm.metrics.metricsData[linkName];
            if (metrics == undefined) {
                console.log("No metrics for:" + linkName + " topo:" + topologyType);
            } else {
                updateLinksOnMap(linkName + "_in", metrics["in"].capacity, metrics["in"].utilization);
                updateLinksOnMap(linkName + "_out", metrics["in"].capacity, metrics["out"].utilization);
            }
        }
    }
}
